<?php

namespace app\admin\model;


use think\db\Query;
use think\Model;

class Comment extends Model
{
    public function userProfile()
    {
        return $this->belongsTo('User','user_id','id');
    }
    public function getCount($id)
    {
        return $this->where('article_id', $id)->count();
    }
    public function userInfo()
    {
        return $this->hasOne(User::class, 'id', 'user_id');
    }
    public function user()
    {
        return $this->belongsTo(User::class , 'user_id' , 'id');
    }
    public function list($data = [])
    {
        /* 
        * @param user_id
        * @param article_id
        */

        $limit = isset($data['limit']) ? $data['limit'] : 10;
        $pageRes = array_key_exists('article_id', $data) ? ['list_rows' => $limit, 'query' => ['id' => $data['article_id']]] : $limit;
        $list = $this->with(['userInfo'  => function (Query $query) {
            $query->field('id,username,head_icon');
        }])->where($data)->order('id desc')->paginate($pageRes);
        foreach ($list as $k => $item) {
            $list[$k]['response_username'] = '';
            $list[$k]['response'] = '';
            $list[$k]['response_id'] = '';
            if ($item['pid'] != 0) {
                $fatherCom =  $this->where('id', $item['pid'])->find();
                if ($fatherCom) {
                    $user = User::where('id', $fatherCom['user_id'])->find();
                    $list[$k]['response_username'] = $user['username'];
                    $list[$k]['response'] = $fatherCom['comment'];
                    $list[$k]['response_id'] = $user['id'];
                }else{
                    $list[$k]['response_username'] = '评论已删除';
                    $list[$k]['response'] = '评论已删除';
                    $list[$k]['response_id'] ='评论已删除';
                }
            }
        }
        $data = [
            'list' => $list,
            'totalNum' => $list->total()
        ];
        return $data;
    }
}
